package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.Permission;
import cn.wolfcode.wms.mapper.PermissionMapper;
import cn.wolfcode.wms.qo.QueryObject;
import cn.wolfcode.wms.service.IPermissionService;
import cn.wolfcode.wms.util.ExpressionFactory;
import cn.wolfcode.wms.util.PageResult;
import cn.wolfcode.wms.util.RequirePermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private ApplicationContext ctx;



    @Override
    public void delete(Long id) {
        if (id != null) {

            permissionMapper.deleteByPrimaryKey(id);
        }
    }

    //加载权限
    public void reload() {
        Collection<Object> ctxs = ctx.getBeansWithAnnotation(Controller.class).values();
        List<String> exps =permissionMapper.selectExpressAll();
        for (Object ctr : ctxs) {
            Method[] ms = ctr.getClass().getDeclaredMethods();
            for (Method m : ms) {
                RequirePermission anno = m.getAnnotation(RequirePermission.class);
                if (anno != null) {
                    //表示方法上中了权限标记,需要与数据库已有权限做对比
                    String exp = ExpressionFactory.buildExpression(m);
                    if (!exps.contains(exp)) {
                        Permission p = new Permission();
                        p.setName(anno.value());
                        p.setExpression(exp);
                        permissionMapper.insert(p);

                    }
                }

            }

        }

    }

    @Override
    public List<Permission> selectall() {
        List<Permission> depts = permissionMapper.selectAll();
        return depts;
    }

    @Override
    public PageResult queryForList(QueryObject qo) {
        int rows = permissionMapper.rows(qo);
        if (rows == 0) {
            return PageResult.EMPTY_RESULT;

        }
        PageResult result = new PageResult(qo.getCurrentPage(), qo.getPageSize(), rows, permissionMapper.queryForList(qo));
        System.out.println(66);
        return result;

    }
}
